<template>
  <div class="edit-page-wrap">
    <Head title="基础信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="edit-form-wrap"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model.trim="ruleForm.roleName"
              placeholder="请输入角色名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="权限范围">
      <template #content>
        <el-tabs v-model="activeTab" class="demo-tabs">
          <el-tab-pane label="电站数据权限" name="station">
            <el-form
              ref="ruleFormRef1"
              :model="ruleForm.stationAuth"
              :rules="rules"
              label-width="80px"
              class="edit-form-wrap"
            >
              <el-form-item label="权限范围" prop="type" class="has-tips">
                <el-radio-group
                  v-model="ruleForm.stationAuth.type"
                  v-for="(item, index) in optionsS.authStation"
                  :key="index"
                  @change="handleStationType"
                >
                  <el-radio :label="item.value">{{ item.label }}</el-radio>
                </el-radio-group>
                <div class="tip">
                  <div class="icon"></div>
                  {{ getStationTip() }}
                </div>
              </el-form-item>
              <el-form-item
                v-if="ruleForm.stationAuth.type === 'ORG'"
                label=""
                prop="treeOrg"
              >
                <QcTree
                  ref="treeOrgRef"
                  :setCheckedKeys="ruleForm.stationAuth.treeOrg"
                  :data="optionsS.orgTree"
                  :showCheckbox="true"
                  :checkStrictly="true"
                  @handleCheck="handleCheckOrg"
                ></QcTree>
              </el-form-item>
              <el-form-item
                v-if="ruleForm.stationAuth.type === 'STATION'"
                label=""
                prop="treeStation"
              >
                <QcTree
                  :setCheckedKeys="ruleForm.stationAuth.treeStation"
                  :data="optionsS.stationTree"
                  :showCheckbox="true"
                  @handleCheck="handleCheckStation"
                ></QcTree>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="用户数据权限" name="user">
            <el-form
              ref="ruleFormRef2"
              :model="ruleForm.userAuth"
              :rules="rules"
              label-width="80px"
              class="edit-form-wrap"
            >
              <el-form-item label="权限范围" prop="type" class="has-tips">
                <el-radio-group
                  v-model="ruleForm.userAuth.type"
                  v-for="(item, index) in optionsS.authUser"
                  :key="index"
                  @change="handleUserType"
                >
                  <el-radio :label="item.value">{{ item.label }}</el-radio>
                </el-radio-group>
                <div class="tip">
                  <div class="icon"></div>
                  {{ getUserTip() }}
                </div>
              </el-form-item>
              <el-form-item
                v-if="ruleForm.userAuth.type === 'ORG'"
                label=""
                prop="treeOrgUser"
              >
                <QcTree
                  ref="treeUserRef"
                  :setCheckedKeys="ruleForm.userAuth.treeOrgUser"
                  :data="optionsS.userOrgTree"
                  :showCheckbox="true"
                  :checkStrictly="true"
                  @handleCheck="handleCheckUserOrg"
                ></QcTree>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="分润数据权限" name="clear">
            <el-form
              ref="ruleFormRef3"
              :model="ruleForm.clearingAuth"
              :rules="rules"
              label-width="100px"
              class="edit-form-wrap"
            >
              <el-form-item label="分润数据权限" prop="type" class="has-tips">
                <el-radio-group
                  v-model="ruleForm.clearingAuth.type"
                  v-for="(item, index) in optionsS.authShare"
                  :key="index"
                  @change="handleShareType"
                >
                  <el-radio :label="item.value">{{ item.label }}</el-radio>
                </el-radio-group>
                <div class="tip">
                  <div class="icon"></div>
                  {{ getShareTip() }}
                </div>
              </el-form-item>
              <el-form-item
                v-if="ruleForm.clearingAuth.type === 'ORG'"
                label=""
                prop="treeOrgClear"
              >
                <QcTree
                  ref="treeClearRef"
                  :setCheckedKeys="ruleForm.clearingAuth.treeOrgClear"
                  :data="optionsS.shareOrgTree"
                  :showCheckbox="true"
                  :checkStrictly="true"
                  @handleCheck="handleCheckShareOrg"
                ></QcTree>
              </el-form-item>
              <el-form-item
                v-if="ruleForm.clearingAuth.type === 'USER'"
                label=""
                prop="treeClear"
              >
                <QcTree
                  :setCheckedKeys="ruleForm.clearingAuth.treeClear"
                  :data="optionsS.shareTree"
                  :showCheckbox="true"
                  @handleCheck="handleCheckShare"
                ></QcTree>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="功能菜单权限" name="menu">
            <el-form
              ref="ruleFormRef4"
              :model="ruleForm.menuAuth"
              :rules="rules"
              label-width="100px"
              class="edit-form-wrap"
            >
              <el-form-item label="功能菜单权限" prop="codes">
                <QcTree
                  ref="treeMenuRef"
                  :setCheckedKeys="ruleForm.menuAuth.codes"
                  :data="optionsS.menuTree"
                  :showCheckbox="true"
                  @handleCheck="handleCheckMenu"
                ></QcTree>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>


<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import {
  AUTH_STATION,
  AUTH_STATION1,
  AUTH_USER,
  AUTH_USER1,
  AUTH_SHARE,
  AUTH_SHARE1,
} from '@/utils/dictionaries';
import {
  orgTreeData,
  stationTreeData,
  userOrgTreeData,
  getShareProfitTree,
  shareTreeData,
} from '@/service/apis/org';
import {
  saveRole,
  updateRole,
  getRoleInfo,
  treeData,
  getAccessAuth,
} from '@/service/apis/auth';
import { FormRules, FormInstance } from 'element-plus';
import { difference } from 'lodash';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();
const ruleFormRef2 = ref<FormInstance>();
const ruleFormRef3 = ref<FormInstance>();
const ruleFormRef4 = ref<FormInstance>();
const treeOrgRef = ref();
const treeUserRef = ref();
const treeClearRef = ref();
const treeMenuRef = ref();

const optionsS = reactive({
  orgTree: [] as any,
  stationTree: [] as any,
  userOrgTree: [] as any,
  shareTree: [] as any,
  shareOrgTree: [] as any,
  menuTree: [] as any,
  menuList: [] as any,
  authStation: [] as any,
  authUser: [] as any,
  authShare: [] as any,
});

// 判断是否有超级管理员选项
getAccessAuth({}).then((res: any) => {
  optionsS.authStation =
    res.stationAuth === 'SUPER' ? AUTH_STATION : AUTH_STATION1;
  optionsS.authUser = res.userAuth === 'SUPER' ? AUTH_USER : AUTH_USER1;
  optionsS.authShare = res.userAuth === 'SUPER' ? AUTH_SHARE : AUTH_SHARE1;
});

// 电站权限数据-企业树数据
const getOrgTree = () => {
  orgTreeData({}).then((res: any) => {
    optionsS.orgTree = res;
  });
};

// 电站权限数据-电站树数据
const getStationTree = () => {
  stationTreeData({}).then((res: any) => {
    optionsS.stationTree = res;
  });
};

// 用户权限数据-企业数据
const getUserOrgTree = () => {
  userOrgTreeData({}).then((res: any) => {
    optionsS.userOrgTree = res;
  });
};

// 分润权限数据-企业数据
const getShareOrgTree = () => {
  shareTreeData({}).then((res: any) => {
    optionsS.shareOrgTree = res;
  });
};

// 分润权限数据-分润数据
const getShareTree = () => {
  getShareProfitTree({}).then((res: any) => {
    optionsS.shareTree = res;
  });
};

// 菜单权限数据-菜单数据
const filterData = (data: any, parent?: any, name?: any) => {
  if (!data) return;
  if (data && data.children && Array.isArray(data.children)) {
    const n = name ? `${name}-${data.label}` : data.label;
    filterData(data.children, data, n);
  }
  if (Array.isArray(data)) {
    data.forEach((d) => filterData(d, parent, name));
  }
  if (!Array.isArray(data) && data.children?.length === 0) {
    let obj = {
      id: data.id,
      label: data.label,
      parentId: data.parentId,
      name: name,
    };
    optionsS.menuList.push(obj);
  }
};
const getMenuTree = () => {
  treeData({}).then((res: any) => {
    optionsS.menuTree = res;
    optionsS.menuList = [];
    filterData(res);
    console.log('optionsS.menuTree----', optionsS.menuList);
  });
};

getMenuTree();

let activeTab = ref('station');
const ruleForm: any = reactive({
  id: '',
  roleName: '', //角色名称
  stationAuth: {
    // 电站数据权限
    type: 'NONE', // 类型
    stationDetails: [] as any, // {operatorId:'',stationId:''}
    treeOrg: [] as any, // 企业树
    treeStation: [] as any, // 电站树
  },
  userAuth: {
    // 用户数据权限
    type: 'NONE', // 类型
    userDetails: [] as any, // {channelId:'',orgId:''}
    treeOrgUser: [] as any, // 企业树
  },
  clearingAuth: {
    // 分润数据权限
    type: 'NONE', // 类型
    clearingDetails: [] as any, // {orgId:'',clearingUserId:''}
    treeClear: [] as any, // 分润树
    treeOrgClear: [] as any, // 企业树
  },
  menuAuth: {
    // 菜单权限数据
    type: '', // 类型 暂不用
    codes: [] as any, // 菜单ID
    parentCodes: [] as any,
  },
});

const checkTreeOrg = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeOrgRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的电站运营商'));
  }
  callback();
};
const checkTreeUser = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeUserRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的用户企业（车辆机构、流量方）'));
  }
  callback();
};
const checkTreeClear = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeClearRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的电站运营商'));
  }
  callback();
};
const rules = reactive<FormRules>({
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  type: [
    { required: true, message: '请选择权限范围', trigger: ['blur', 'change'] },
  ],
  treeOrg: [
    { required: true, message: '请选择企业数据', trigger: ['blur', 'change'] },
    { validator: checkTreeOrg, trigger: ['blur', 'change'] },
  ],
  treeStation: [
    { required: true, message: '请选择电站数据', trigger: ['blur', 'change'] },
  ],
  treeOrgUser: [
    { required: true, message: '请选择企业数据', trigger: ['blur', 'change'] },
    { validator: checkTreeUser, trigger: ['blur', 'change'] },
  ],
  treeClear: [
    {
      required: true,
      message: '请选择分润方数据',
      trigger: ['blur', 'change'],
    },
  ],
  treeOrgClear: [
    { required: true, message: '请选择企业数据', trigger: ['blur', 'change'] },
    { validator: checkTreeClear, trigger: ['blur', 'change'] },
  ],
});

const getStationTip = () => {
  if (ruleForm.stationAuth.type === 'NONE') {
    return '当前角色无电站权限';
  } else if (ruleForm.stationAuth.type === 'SUPER') {
    return '管理员所属企业及其子企业的所有电站均在权限范围内';
  } else if (ruleForm.stationAuth.type === 'ORG') {
    return '选定运营商后，该运营商所有的电站均授权，含授权后新增的电站';
  } else if (ruleForm.stationAuth.type === 'STATION') {
    return '选定单电站后，仅所选电站授权，授权后新增的电站不在授权范围内';
  }
  return '';
};

const getUserTip = () => {
  if (ruleForm.userAuth.type === 'NONE') {
    return '当前角色无用户权限';
  } else if (ruleForm.userAuth.type === 'SUPER') {
    return '管理员所属企业及其子企业的所有用户均在权限范围内';
  } else if (ruleForm.userAuth.type === 'ORG') {
    return '选定企业后，该企业所有的用户均授权，含授权后新增的用户';
  }
  return '';
};

const getShareTip = () => {
  if (ruleForm.clearingAuth.type === 'NONE') {
    return '当前角色无任何分润方分润结果查看权限';
  } else if (ruleForm.clearingAuth.type === 'SUPER') {
    return '管理员所属企业及其子企业的所有分润方分润结果均在权限范围内';
  } else if (ruleForm.clearingAuth.type === 'ORG') {
    return '选定运营商后，该运营商所有的分润方分润结果均授权，含授权后新增的分润方';
  } else if (ruleForm.clearingAuth.type === 'USER') {
    return '选定单分润方后，仅所选分润方的分润结果授权';
  }
  return '';
};

const handleStationType = (e: any) => {
  if (ruleForm.stationAuth.type === 'ORG' && optionsS.orgTree?.length === 0) {
    getOrgTree();
  } else if (
    ruleForm.stationAuth.type === 'STATION' &&
    optionsS.stationTree?.length === 0
  ) {
    getStationTree();
  }
};
const handleUserType = (e: any) => {
  if (ruleForm.userAuth.type === 'ORG' && optionsS.userOrgTree?.length === 0) {
    getUserOrgTree();
  }
};

const handleShareType = (e: any) => {
  if (
    ruleForm.clearingAuth.type === 'ORG' &&
    optionsS.shareOrgTree?.length === 0
  ) {
    getShareOrgTree();
  } else if (
    ruleForm.clearingAuth.type === 'USER' &&
    optionsS.shareTree?.length === 0
  ) {
    getShareTree();
  }
};

const handleCheckOrg = (data: any, checkedData: any, checkedChildData: any) => {
  ruleForm.stationAuth.treeOrg = checkedChildData;
  ruleFormRef1.value?.validateField('treeOrg');
};
const handleCheckStation = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.stationAuth.treeStation = checkedChildData;
  ruleFormRef1.value?.validateField('treeStation');
};
const handleCheckUserOrg = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.userAuth.treeOrgUser = checkedChildData;
  ruleFormRef2.value?.validateField('treeOrgUser');
};
const handleCheckShare = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.clearingAuth.treeClear = checkedChildData;
  ruleFormRef3.value?.validateField('treeClear');
};
const handleCheckShareOrg = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.clearingAuth.treeOrgClear = checkedChildData;
  ruleFormRef3.value?.validateField('treeOrgClear');
};
const handleCheckMenu = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.menuAuth.codes = checkedChildData;
  const arr = [...checkedData.checkedKeys, ...checkedData.halfCheckedKeys];
  ruleForm.menuAuth.parentCodes = difference(arr, checkedChildData);
};

if (id) {
  getRoleInfo({ id: id }).then((res: any) => {
    ruleForm.id = res.id;
    ruleForm.roleName = res.roleName;
    ruleForm.stationAuth.type = res.stationAuth.type;
    if (res.stationAuth.type === 'ORG') {
      ruleForm.stationAuth.treeOrg = res.stationAuth.stationDetails.map(
        (item: any) => item.stationId
      );
      getOrgTree();
    } else if (res.stationAuth.type === 'STATION') {
      ruleForm.stationAuth.treeStation = res.stationAuth.stationDetails.map(
        (item: any) => item.stationId
      );
      getStationTree();
    }

    ruleForm.userAuth.type = res.userAuth.type;
    if (res.userAuth.type === 'ORG') {
      ruleForm.userAuth.treeOrgUser = res.userAuth.userDetails.map(
        (item: any) => item.orgId
      );
      getUserOrgTree();
    }

    ruleForm.clearingAuth.type = res.clearingAuth.type;
    if (ruleForm.clearingAuth.type === 'ORG') {
      ruleForm.clearingAuth.treeOrgClear =
        res.clearingAuth.clearingDetails?.map((item: any) => item.orgId);
      getShareOrgTree();
    } else if (ruleForm.clearingAuth.type === 'USER') {
      ruleForm.clearingAuth.treeClear = res.clearingAuth.clearingDetails?.map(
        (item: any) => item.clearingUserId
      );
      getShareTree();
    }

    ruleForm.menuAuth.codes = res.menuAuth.codes;
    ruleForm.menuAuth.parentCodes = res.menuAuth.parentCodes;
  });
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (
    !ruleFormRef.value ||
    !ruleFormRef1.value ||
    !ruleFormRef2.value ||
    !ruleFormRef3.value ||
    !ruleFormRef4.value
  )
    return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef1.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef2.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef3.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef4.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormRef1.value.scrollToField(key);
        ruleFormRef2.value.scrollToField(key);
        ruleFormRef3.value.scrollToField(key);
        ruleFormRef4.value.scrollToField(key);
        break;
      }
    }
    return;
  }

  const treeMenu = treeMenuRef.value.getCheckedNodes();
  const mLen = treeMenu.length;
  if (mLen > 0) {
    let mFlag = false;
    let msg = '';
    for (let i = 0; i < mLen; i++) {
      const item = treeMenu[i];
      if (
        item.label !== '查看' &&
        item.label !== '大屏' &&
        item.id !== '1241' &&
        item.id !== '1242' &&
        item.id !== '1243' &&
        item.children?.length === 0
      ) {
        const obj = treeMenu.find(
          (it: any) => it.parentId === item.parentId && it.label === '查看'
        );
        if (!obj) {
          console.log('111---', item);
          mFlag = true;
          const obj1 = optionsS.menuList.find((it: any) => item.id === it.id);
          msg = `您勾选了“${obj1.name}”的操作权限，没有勾选功能查看权限，需要勾选！`;
          break;
        }
      }
    }
    if (mFlag) {
      ElMessageBox.alert(msg, '提示', {
        confirmButtonText: '确认',
        type: 'warning',
      });
      return;
    }
  }

  if (ruleForm.stationAuth.type === 'ORG') {
    // ruleForm.stationAuth.stationDetails = ruleForm.stationAuth.treeOrg.map(
    //   (item: any) => ({
    //     stationId: item,
    //   })
    // );
    ruleForm.stationAuth.stationDetails = [];
    const treeOrg = treeOrgRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        ruleForm.stationAuth.stationDetails.push({
          stationId: item.id,
        });
      }
    });
  } else if (ruleForm.stationAuth.type === 'STATION') {
    ruleForm.stationAuth.stationDetails = ruleForm.stationAuth.treeStation.map(
      (item: any) => ({
        stationId: item,
      })
    );
  }

  if (ruleForm.userAuth.type === 'ORG') {
    // ruleForm.userAuth.userDetails = ruleForm.userAuth.treeOrgUser.map(
    //   (item: any) => ({
    //     orgId: item,
    //   })
    // );
    ruleForm.userAuth.userDetails = [];
    const treeOrg = treeUserRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        ruleForm.userAuth.userDetails.push({
          orgId: item.id,
        });
      }
    });
  }

  if (ruleForm.clearingAuth.type === 'ORG') {
    // ruleForm.clearingAuth.clearingDetails =
    //   ruleForm.clearingAuth.treeOrgClear?.map((item: any) => ({
    //     orgId: item,
    //   }));
    ruleForm.clearingAuth.clearingDetails = [];
    const treeOrg = treeClearRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        ruleForm.clearingAuth.clearingDetails.push({
          orgId: item.id,
        });
      }
    });
  } else if (ruleForm.clearingAuth.type === 'USER') {
    ruleForm.clearingAuth.clearingDetails =
      ruleForm.clearingAuth.treeClear?.map((item: any) => ({
        clearingUserId: item,
      }));
  }

  console.log('ru---', ruleForm);
  if (id) {
    updateRole(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    saveRole(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>